<template>
  <div class="finance-container">
    <!-- 搜索区域 -->
    <div class="search-box">
      <el-input
        v-model="searchParams.categoryName"
        placeholder="请输入类别名称"
        clearable
        style="width: 300px"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button @click="handleReset">
        <el-icon><Refresh /></el-icon>重置
      </el-button>
    </div>

    <!-- 操作按钮 -->
    <div class="action-box">
      <el-button 
        v-if="userRid !== 2"
        type="primary" 
        @click="handleAdd"
      >
        <el-icon><Plus /></el-icon>新增
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading"
      height="calc(100vh - 260px)"
    >
      <el-table-column prop="categoryNumber" label="类别编号" width="120" />
      <el-table-column prop="categoryName" label="类别名称" width="150" />
      <el-table-column prop="remark" label="备注" show-overflow-tooltip>
        <template #default="{ row }">
          {{ formatNullValue(row.remark) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.state)" size="small">
            {{ getStatusText(row.state) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatTime(row.creatTime) }}
        </template>
      </el-table-column>
      <el-table-column label="创建人" width="120">
        <template #default="{ row }">
          {{ formatNullValue(row.creatName) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <!-- 未审批状态：RID != 2的用户可以编辑删除，RID == 2的用户可以审批 -->
          <template v-if="row.state === 0">
            <el-button 
              v-if="userRid !== 2"
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userRid !== 2"
              size="small"
              type="danger"
              @click="handleDelete(row.financialCategoryId)"
            >
              删除
            </el-button>
            <el-button
              v-if="userRid === 2"
              size="small"
              type="warning"
              @click="handleApprove(row)"
            >
              审批
            </el-button>
          </template>
          
          <!-- 已审批状态：所有用户只能查看 -->
          <template v-else>
            <el-button
              size="small"
              type="info"
              @click="handleView(row)"
            >
              查看
            </el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[15, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑/查看对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="getDialogTitle()"
      width="50%"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        :class="{ 'view-mode': formData.financialCategoryId && !isEdit }"
      >
        <el-form-item label="类别编号" prop="categoryNumber">
          <el-input v-model="formData.categoryNumber" :readonly="formData.financialCategoryId && !isEdit" />
        </el-form-item>
        <el-form-item label="类别名称" prop="categoryName">
          <el-input v-model="formData.categoryName" :readonly="formData.financialCategoryId && !isEdit" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :readonly="formData.financialCategoryId && !isEdit" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">{{ formData.financialCategoryId && !isEdit ? '关闭' : '取消' }}</el-button>
        <el-button v-if="!(formData.financialCategoryId && !isEdit)" type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="审批财务类别"
      width="60%"
      class="approval-dialog"
    >
      <div class="approval-content">
        <!-- 财务类别信息 -->
        <div class="category-info">
          <h4>财务类别信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="类别编号">
              {{ approveDialogRow.categoryNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="类别名称">
              {{ approveDialogRow.categoryName }}
            </el-descriptions-item>
            <el-descriptions-item label="备注">
              {{ formatNullValue(approveDialogRow.remark) }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatTime(approveDialogRow.creatTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="创建人">
              {{ formatNullValue(approveDialogRow.creatName) }}
            </el-descriptions-item>
            <el-descriptions-item label="当前状态">
              <el-tag :type="getStatusType(approveDialogRow.state)" size="small">
                {{ getStatusText(approveDialogRow.state) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 审批表单 -->
        <div class="approval-form">
          <h4>审批意见</h4>
          <el-form :model="approveForm" label-width="80px">
            <el-form-item label="审批结果" required>
              <el-radio-group v-model="approveForm.approvalResult">
                <el-radio :label="1">同意</el-radio>
                <el-radio :label="2">驳回</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审批备注">
              <el-input
                v-model="approveForm.approvalNote"
                type="textarea"
                :rows="3"
                placeholder="请输入审批备注（可选）"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApproval">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import { type AxiosError } from "axios";
import http from "@/http/axiosHelper";
import { finread, finwrite } from "@/systeamaxios/sysaxiosHelpers";
import { useCounterStore } from "@/stores/counter";

// 类型定义
interface FinancialCategory {
  financialCategoryId: number;
  categoryNumber: string;
  categoryName: string;
  remark?: string | null;
  creatTime?: string | null;
  creatName?: string | null;
  updateTime?: string | null;
  updateName?: string | null;
  deleteTime?: string | null;
  deleteName?: string | null;
  isDel?: boolean;
  state?: number; // 新增状态字段
}

interface ApiResponse {
  code: number;
  message: string;
  totalPage: number;
  totalCount: number;
  pageDatas: FinancialCategory[];
  data: any;
}

// 接口基础路径
const API_BASE = {
  show: "/finread/api/FinancialCategory/ShowFinancialCategoryCommand",
  add: "/finwrite/api/FinancialCategory/AddFinancialCategoryCommand",
  update: "/finwrite/api/FinancialCategory/UpdFinancialCategoryCommand",
  delete: "/finwrite/api/FinancialCategory/DelFinancialCategoryCommand",
};
/*const API_BASE = {
  show: "/api/FinancialCategory/ShowFinancialCategoryCommand",
  add: "/api/FinancialCategory/AddFinancialCategoryCommand",
  update: "/api/FinancialCategory/UpdFinancialCategoryCommand",
  delete: "/api/FinancialCategory/DelFinancialCategoryCommand",
};*/

// 响应式数据
const tableData = ref<FinancialCategory[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

// 审批相关数据
const approveDialogVisible = ref(false);
const approveDialogRow = reactive<FinancialCategory>({
  financialCategoryId: 0,
  categoryNumber: "",
  categoryName: "",
  remark: "",
  creatTime: "",
  creatName: "",
  state: 0,
});
const approveForm = reactive({
  approvalResult: 1, // 1: 同意, 2: 驳回
  approvalNote: "",
});

// 分页参数
const pagination = reactive({
  pageIndex: 1,
  pageSize: 15, // 修改默认分页为15条
  total: 0,
});

// 搜索参数
const searchParams = reactive({
  categoryName: "",
});

// 表单数据
const formData = reactive<FinancialCategory>({
  financialCategoryId: 0,
  categoryNumber: "",
  categoryName: "",
  remark: "",
  creatName: "admin",
  updateName: "admin",
  creatTime: "2025-07-24T13:12:04.753Z",
  updateTime: "2025-07-24T13:12:04.753Z",
  deleteTime: "2025-07-24T13:12:04.753Z",
  deleteName: "",
  isDel: false,
});

// 表单验证规则
const formRules = {
  categoryNumber: [
    { required: true, message: "请输入类别编号", trigger: "blur" },
  ],
  categoryName: [
    { required: true, message: "请输入类别名称", trigger: "blur" },
  ],
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    // 权限控制：RID != 2的用户只能看到自己的数据，RID == 2的用户可以看到所有人的数据
    const currentRid = userRid.value;
    const ridParam = currentRid !== 2 ? currentRid : undefined;

    console.log("当前用户RID:", currentRid);
    console.log("查询参数rid:", ridParam);

    const response = await http.get<ApiResponse>(API_BASE.show, {
      params: {
        CategoryName: searchParams.categoryName,
        PageIndex: pagination.pageIndex,
        PageSize: pagination.pageSize,
        rid: ridParam, // 添加RID权限控制
      },
    });

    if (response.data.code === 200) {
      tableData.value = response.data.pageDatas || [];
      pagination.total = response.data.totalCount || 0;
      ElMessage.success(response.data.message);
    } else {
      ElMessage.warning(response.data.message || "获取数据失败");
    }
  } catch (error) {
    const err = error as AxiosError<ApiResponse>;
    ElMessage.error(err.response?.data?.message || "请求失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const handleSearch = () => {
  pagination.pageIndex = 1;
  fetchData();
};

// 重置搜索
const handleReset = () => {
  searchParams.categoryName = "";
  handleSearch();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchData();
};

// 页码变化
const handlePageChange = (page: number) => {
  pagination.pageIndex = page;
  fetchData();
};

// 新增
const handleAdd = () => {
  // 权限验证：rid==2的用户不能新增
  if (userRid.value === 2) {
    ElMessage.error("您没有新增权限");
    return;
  }
  
  isEdit.value = false;
  Object.assign(formData, {
    financialCategoryId: 0,
    categoryNumber: "",
    categoryName: "",
    remark: "",
    creatName: "admin",
  });
  dialogVisible.value = true;
};

// 编辑
// 获取对话框标题
const getDialogTitle = () => {
  if (formData.financialCategoryId && !isEdit.value) {
    return '查看财务类别';
  }
  return isEdit.value ? '编辑财务类别' : '新增财务类别';
};

// 查看
const handleView = (row: FinancialCategory) => {
  isEdit.value = false;
  formData.financialCategoryId = row.financialCategoryId;
  formData.categoryNumber = row.categoryNumber;
  formData.categoryName = row.categoryName;
  formData.remark = row.remark || "";
  formData.updateName = "admin";
  dialogVisible.value = true;
};

const handleEdit = (row: FinancialCategory) => {
  // 权限验证：rid==2的用户不能编辑
  if (userRid.value === 2) {
    ElMessage.error("您没有编辑权限");
    return;
  }
  
  isEdit.value = true;
  formData.financialCategoryId = row.financialCategoryId;
  formData.categoryNumber = row.categoryNumber;
  formData.categoryName = row.categoryName;
  formData.remark = row.remark || "";
  formData.updateName = "admin";
  dialogVisible.value = true;
};

// 删除
const handleDelete = async (id: number) => {
  // 权限验证：rid==2的用户不能删除
  if (userRid.value === 2) {
    ElMessage.error("您没有删除权限");
    return;
  }
  
  try {
    await ElMessageBox.confirm("确认删除该记录吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await http.post(
      `${API_BASE.delete}?financialCategoryId=${id}`
    );
    if (response.data.code === 200) {
      ElMessage.success(response.data.message);
      fetchData();
    } else {
      ElMessage.warning(response.data.message || "删除失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      const err = error as AxiosError<ApiResponse>;
      ElMessage.error(err.response?.data?.message || "删除失败");
    }
  }
};

// 提交表单
const submitForm = async () => {
  // 权限验证：rid==2的用户不能提交表单
  if (userRid.value === 2) {
    ElMessage.error("您没有操作权限");
    return;
  }
  
  try {
    await formRef.value?.validate();

    let response;
    if (isEdit.value) {
      response = await http.post(API_BASE.update, formData);
    } else {
      response = await http.post(API_BASE.add, formData);
    }

    if (response.data.code == 200) {
      ElMessage.success(response.data.message);
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.warning(response.data.message || "操作失败");
    }
  } catch (error) {
    const err = error as AxiosError<ApiResponse>;
    ElMessage.error(err.response?.data?.message || "提交失败");
  }
};

// 审批处理
const handleApprove = (row: FinancialCategory) => {
  // 权限验证：只有rid==2的用户才能审批
  if (userRid.value !== 2) {
    ElMessage.error("您没有审批权限，只有管理员才能审批");
    return;
  }
  
  // 状态验证：只有待审批状态才能审批
  if (row.state !== 0) {
    ElMessage.warning("只有待审批状态的记录才能进行审批");
    return;
  }
  
  approveDialogRow.financialCategoryId = row.financialCategoryId;
  approveDialogRow.categoryNumber = row.categoryNumber;
  approveDialogRow.categoryName = row.categoryName;
  approveDialogRow.remark = row.remark || "";
  approveDialogRow.creatTime = row.creatTime;
  approveDialogRow.creatName = row.creatName;
  approveDialogRow.state = row.state || 0;
  approveForm.approvalResult = 1; // 默认同意
  approveForm.approvalNote = "";
  approveDialogVisible.value = true;
};

// 提交审批
const submitApproval = async () => {
  try {
    // 权限验证：再次确认用户有审批权限
    if (userRid.value !== 2) {
      ElMessage.error("您没有审批权限，只有管理员才能审批");
      return;
    }
    
    // 验证审批结果
    if (!approveForm.approvalResult) {
      ElMessage.warning("请选择审批结果");
      return;
    }
    
    const response = await http.post(
      `${API_BASE.update}?financialCategoryId=${approveDialogRow.financialCategoryId}`,
      {
        state: approveForm.approvalResult,
        approvalNote: approveForm.approvalNote,
        updateTime: new Date().toISOString(),
        updateName: counterStore.Account.name || "admin",
      }
    );
    
    if (response.data.code === 200) {
      ElMessage.success("审批成功");
      approveDialogVisible.value = false;
      fetchData(); // 刷新数据
    } else {
      ElMessage.warning(response.data.message || "审批失败");
    }
  } catch (error) {
    const err = error as AxiosError<ApiResponse>;
    ElMessage.error(err.response?.data?.message || "审批失败，请重试");
  }
};

// 格式化时间
const formatTime = (time: string | null | undefined) => {
  if (!time) return "-";
  return new Date(time).toLocaleString();
};

// 格式化空值
const formatNullValue = (value: any) => {
  return value === null || value === undefined || value === "" ? "-" : value;
};

// 初始化Pinia store
const counterStore = useCounterStore();

// 获取用户rid - 使用computed从store获取
const userRid = computed(() => {
  return counterStore.Account.rid || 0;
});

// 状态处理函数
const getStatusType = (state: number | undefined) => {
  switch (state) {
    case 0:
      return "info"; // 待审批
    case 1:
      return "success"; // 已通过
    case 2:
      return "danger"; // 已驳回
    default:
      return "info";
  }
};

const getStatusText = (state: number | undefined) => {
  switch (state) {
    case 0:
      return "待审批";
    case 1:
      return "已通过";
    case 2:
      return "已驳回";
    default:
      return "待审批";
  }
};

// 初始化加载数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.finance-container {
  padding: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-box {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.action-box {
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.approval-dialog .el-dialog__body {
  padding: 20px;
}

.approval-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.category-info h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.approval-form h4 {
  margin-bottom: 15px;
  color: #303133;
  font-size: 16px;
  border-bottom: 2px solid #67c23a;
  padding-bottom: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.category-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.approval-form {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

/* 审批按钮样式 */
.el-button--warning {
  margin-left: 8px;
}

/* 状态标签样式 */
.el-tag {
  font-weight: 500;
}

/* 查看模式样式 */
.view-mode .el-input__inner,
.view-mode .el-textarea__inner {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #606266;
}
</style>
